package com.ruoyi.system.utils.modbus;

import com.ruoyi.system.domain.MrDevice;
import com.serotonin.modbus4j.ModbusSlaveSet;
import com.serotonin.modbus4j.ip.tcp.TcpSlave;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.task.TaskExecutor;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据上报 modbus
 */
public class ModbusTCPSlave {
    static Log log = LogFactory.getLog(ModbusTCPSlave.class);
    public static void main(String[] args) {
        int port = 42001;
        int slaveId = 1;
        List<MrDevice> mrDevices = new ArrayList<>();
        MrDevice mrDevice = new MrDevice();
        mrDevice.setRemark("125");
        mrDevice.setModality("BA");
        mrDevice.setRegisterAddress("3");
        mrDevices.add(mrDevice);
        mrDevice = new MrDevice();
        mrDevice.setRemark("true");
        mrDevice.setModality("MR");
        mrDevice.setRegisterAddress("5");
        mrDevices.add(mrDevice);

        run(port, slaveId, mrDevices);
    }

    public static void run(int port, int slaveId, List<MrDevice> mrDevices) {
        /* createSlave方法执行完成后，会进行监听，影响之后的业务运行，需要以线程的方式进行启动 */
//        new Thread(ModbusTCPSlave::createSalve).start();
        new Thread(() -> {
            createSalve(port, slaveId, mrDevices);
        }).start();
//        new TaskExecutor() {
//            public void execute() {
//                createSalve(port, slaveId, mrDevices);
//            }
//
//            @Override
//            public void execute(Runnable task) {
//                createSalve(port, slaveId, mrDevices);
//            }
//        }.execute();

        /* 为保证在进行点表数据初始化的时候slave已经启动完成，在此处进行了1s的休眠 */
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        /* 开始进行点表的初始化数据写入 */
        // InitModbusSlave();
    }

    /**
     * @description 创建ModbusTCP服务器
     */
    private static void createSalve(int port, int slaveId, List<MrDevice> mrDevices) {
        //创建modbus工厂
//        ModbusFactory modbusFactory = new ModbusFactory();
        //创建TCP服务端
        // final ModbusSlaveSet salve = modbusFactory.createTcpSlave(false);
        final ModbusSlaveSet salve = new TcpSlave(port, false);

        //向过程影像区添加数据
        salve.addProcessImage(Register.getModscanProcessImage(slaveId, mrDevices));
        //获取寄存器
        salve.getProcessImage(slaveId);
        try {
            salve.start();
            log.info("【信息化上报任务】start");
        } catch (Exception e) {
            log.info("【信息化上报任务】异常：" + e.getMessage());
            e.fillInStackTrace();
        }
    }
}
